package com.wonderfulWeather.app.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.*;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.*;
import com.wonderfulWeather.app.R;
import com.wonderfulWeather.app.WeatherApplication;
import com.wonderfulWeather.app.model.County;
import com.wonderfulWeather.app.service.AutoUpdateService;
import com.wonderfulWeather.app.util.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by kevin on 2014/12/23.
 *
 * Weather活动
 */
public class WeatherActivity extends Activity implements View.OnClickListener{
    private MyPagerAdapter pagerAdapter;
    private ViewPager viewPager;
    private List<View> viewList;
    private int currIndex=0;
    private List<String> codeList;
    private LinearLayout pagerLayout;
    private int PageCount=1;
    private Intent sintent;
    private int vPageCount=2;


    private Button switchCity,refreshInfo;
    private ViewFlipper viewFlipper;
    private static final int SWIPE_MIN_DISTANCE=120;
    //private static final int SWIPE_MAC_OFF_PATH=250;
    //private static final int SWIPE_THRESHOLD_VELOCITY=200;
    Animation slidTopIn,slidTopOut,slidBottomIn,slidBottomOut;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.getMenuInflater().inflate(R.menu.main_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId())
        {
            case R.id.menuitem_remove:
                if(viewList.size()>1) {
                    CharSequence cityName=((TextView)viewList.get(currIndex).findViewById(R.id.city_name_page)).getText();

                    for(int i=0;i<viewList.size();i++)
                    {
                        LogUtil.d("List","index["+ i +"]="+codeList.get(i));
                    }
                    LogUtil.d("currIndex","BeforeChange currIndex="+currIndex);

                    String currCode=codeList.get(currIndex);
                    pagerAdapter.removeView(currIndex);
                    if(currIndex>=viewList.size()){currIndex=viewList.size()-1;}
                    viewPager.setCurrentItem(currIndex);
                    SharedPreferences ps=this.getSharedPreferences(CommonUtility.SHARED_PREF_NAME,MODE_PRIVATE);
                    String Codes= ps.getString("codes","");
                    Codes= Codes.replace(currCode+"|","");
                    SharedPreferences.Editor editor= ps.edit();
                    editor.putString("codes",Codes);
                    editor.apply();
                    LogUtil.d("currIndex","Changed currIndex="+currIndex);
                    for(int i=0;i<viewList.size();i++)
                    {
                        LogUtil.d("List","index["+ i +"]="+codeList.get(i));
                    }

                    if(viewList.size()==1)
                    {
                        pagerLayout.setVisibility(View.GONE);
                    }

                    Toast.makeText(this,"城市 "+ cityName +" 已删除",Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(this,"就剩一个城市了，真不能再删了",Toast.LENGTH_SHORT).show();
                }
                return true;
           /* case R.id.menuitem_default:
                DefaultIndex=currIndex;
                SharedPreferences.Editor editor= this.getSharedPreferences(CommonUtility.SHARED_PREF_NAME,MODE_PRIVATE).edit();
                editor.putInt("defaultIndex", currIndex);
                editor.apply();
                Toast.makeText(this,"已将 "+ ((TextView)viewList.get(currIndex).findViewById(R.id.city_name_page)).getText() +" 设为默认城市",Toast.LENGTH_SHORT).show();
                return true;*/
        }
        return false;
    }

    DisplayUtil.Size screen_dip;
    float screen_Density;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.weather_layout);

        slidTopIn= AnimationUtils.loadAnimation(this, R.anim.solid_top_in);
        slidTopOut= AnimationUtils.loadAnimation(this,R.anim.solid_top_out);
        slidBottomIn= AnimationUtils.loadAnimation(this,R.anim.solid_bottom_in);
        slidBottomOut= AnimationUtils.loadAnimation(this,R.anim.solid_bottom_out);


        switchCity=(Button)findViewById(R.id.switch_city);
        refreshInfo=(Button)findViewById(R.id.btnRefresh);
        //按钮事件
        switchCity.setOnClickListener(this);
        refreshInfo.setOnClickListener(this);
        //获取屏幕信息
        screen_dip=DisplayUtil.getScreenSizeForDpi();
        screen_Density=DisplayUtil.getScreenDensity();

        //初始化数据
        InitLoadData();
        //初始化布局
        initView();
    }


    private void initView()
    {
        if(viewPager!=null){return;}

        LayoutInflater lf=getLayoutInflater();
        viewList=new ArrayList<View>();
        //加载视图
        LayoutInflater li=  this.getLayoutInflater();
        for(int i=0;i<PageCount;i++) {
            View v=li.inflate(R.layout.weather_page,null);
            ((TextView)v.findViewById(R.id.currtemp_page)).setText("");
            ((TextView)v.findViewById(R.id.weather_desp_page)).setText("");
            ((TextView)v.findViewById(R.id.wind_page)).setText("");
            ((TextView)v.findViewById(R.id.pm25_page)).setText("");
            v.setBackgroundResource(R.drawable.bg_1_d);
            viewList.add(v);
            //showWeatherMoreDay();
        }
        viewPager=(ViewPager)findViewById(R.id.weatherPager);
        //滚动指示的小圆
        pagerLayout = (LinearLayout) findViewById(R.id.pager_page);
        if(viewList.size()>1) {
            pagerLayout.setVisibility(View.VISIBLE);
            for (int i = 0; i < viewList.size(); i++) {
                ImageView img = new ImageView(this);
                if (i == 0) {
                    img.setImageResource(R.drawable.dot_light);
                } else {
                    img.setImageResource(R.drawable.dot_normal);
                }
                pagerLayout.addView(img);
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) img.getLayoutParams();
                lp.setMargins(4, 2, 4, 2);
                img.setLayoutParams(lp);
            }
        }
        else
        {
            pagerLayout.setVisibility(View.GONE);
        }
        pagerAdapter=new MyPagerAdapter(viewList);
        viewPager.setAdapter(pagerAdapter);
        viewPager.setCurrentItem(0);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                currIndex=i;
                LogUtil.d("selected","currIndex="+i);
                //指定当前的ViewFlipper
                viewFlipper=(ViewFlipper)viewList.get(currIndex).findViewById(R.id.viewFlipper);
                for(int j=0;j<viewList.size();j++) {
                    if(i==j) {
                        ((ImageView) pagerLayout.getChildAt(j)).setImageResource(R.drawable.dot_light);
                        String code=codeList.get(j);
                        if(!code.equals("")) {
                            queryWeatherInfo(code);
                        }
                    }
                    else
                    {
                        ((ImageView) pagerLayout.getChildAt(j)).setImageResource(R.drawable.dot_normal);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

        viewFlipper=(ViewFlipper)viewList.get(currIndex).findViewById(R.id.viewFlipper);
        //滚动到当前页面
        viewPager.setCurrentItem(currIndex);
    }


    private void InitLoadData() {
        String countyCode = getIntent().getStringExtra("county_code");
        String current_code = this.getSharedPreferences(CommonUtility.SHARED_PREF_NAME, MODE_PRIVATE).getString("current_code", "");
        //获取当前Page的总数
        String codes=this.getSharedPreferences(CommonUtility.SHARED_PREF_NAME, MODE_PRIVATE).getString("codes", "");
        codeList=new ArrayList<String>();
        if(!TextUtils.isEmpty(codes))
        {
            codeList.addAll(Arrays.asList(codes.split("\\|")));
            PageCount=codeList.size();
            if(!TextUtils.isEmpty(countyCode))
            {
                for (int i=0;i<codeList.size();i++)
                {
                    if (countyCode.equals(codeList.get(i))) {
                        currIndex = i;
                    }
                }
            }
        }
        if(PageCount<1){PageCount=1;}
        //开始获取初始数据
        LogUtil.d("weather","current_code="+current_code+",ext county="+countyCode);
        if(!TextUtils.isEmpty(countyCode) || TextUtils.isEmpty(current_code))
        {
            if(TextUtils.isEmpty(countyCode)) {
                LogUtil.d("OnCreate","Begin get current county");
                County current_county=WeatherApplication.getCurrentCounty();
                if(current_county!=null)
                {
                    codeList.add(current_county.getCode());
                    PageCount=codeList.size();
                    LogUtil.d("weather","get current county "+current_county.getCode());
                    queryWeatherInfo(current_county.getCode());
                }
                else
                {
                    LogUtil.d("weather","choose county ");
                    Intent intent = new Intent(WeatherActivity.this, ChooseAreaActivity.class);
                    startActivity(intent);
                    finish();
                }
            }else{

                LogUtil.d("weather","query county ");
                queryWeatherInfo(countyCode);
            }
        }
        else
        {
            LogUtil.d("weather","show weather");
            //设置当前为默认
            try {
                showWeather();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        if(sintent==null) {
            sintent = new Intent(WeatherActivity.this, AutoUpdateService.class);
            startService(sintent);
        }
    }




    private boolean isNeedQuery(String weatherCode)
    {
        SharedPreferences prefs=this.getSharedPreferences(weatherCode, MODE_PRIVATE);
        boolean isQuery=true;
        if(prefs!=null)
        {
            try {//一小时以内的不再查询
                String lastQuery = prefs.getString("lastQuery", "");
                SimpleDateFormat dd = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                java.util.Calendar calStart = java.util.Calendar.getInstance();
                calStart.setTime(dd.parse(lastQuery));

                long begin=calStart.getTimeInMillis();
                long end = System.currentTimeMillis();

                LogUtil.d("LastUpdate","code:"+weatherCode+",On:"+lastQuery+",LMS:"+begin+",NMS="+end+",CMS:"+(end-begin));
                if (end-begin>3600000)
                {
                    isQuery=true;
                }
                else
                {
                    isQuery=false;
                }
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
        }
        return  isQuery;
    }

    /**
     * 查询天气代码所对应的天气信息
     * */
    private void queryWeatherInfo(String weatherCode)
    {
        if(weatherCode.equals(CommonUtility.LOCATION_CODE))
        {
            weatherCode=WeatherActivity.this.getSharedPreferences(CommonUtility.SHARED_PREF_NAME, MODE_PRIVATE).getString("location", "");
        }
        if(TextUtils.isEmpty(weatherCode)){
            LogUtil.d("qyertWeatherInfo","Get Location Weather,but Location Code is null");
            return;
        }
        boolean isQuery=isNeedQuery(weatherCode);
        LogUtil.d("query","is NeedQuery="+isQuery);
        SharedPreferences.Editor editor = this.getSharedPreferences(CommonUtility.SHARED_PREF_NAME, MODE_PRIVATE).edit();
        editor.putString("current_code", weatherCode);
        editor.apply();
        if(isQuery) {
            queryFromServer(CommonUtility.getWeatherUrl(weatherCode), "weatherCode");
        }
        else
        {
            showWeather();
        }
    }

    /**
     * 根据传入的地址和类型去向服务器查询天气代号或者天气信息
     * */
    private void queryFromServer(final String address,final String type)
    {
        LogUtil.d("HTTP",address);

        HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
            @Override
            public void onFinish(String response) {

                LogUtil.d(type, response);

                if ("weatherCode".equals(type)) {
                    if (Utility.handleWeatherResponse(WeatherActivity.this, response)) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showWeather();
                            }
                        });
                    }
                } else if ("weatherMore".equals(type)) {
                    if (Utility.handleWeatherMoreResponse(WeatherActivity.this, response)) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showWeatherMoreDay();
                            }
                        });
                    }
                }
            }

            @Override
            public void onError(Exception e) {
               /* runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        publishText.setText("同步失败");
                    }
                });*/
            }
        });
    }

    private void showWeatherMoreDay()
    {
        try {
            View v = viewList.get(currIndex);
            LogUtil.d("init", "screenWidth_dip=" + screen_dip.getWidth() + ",screen_Density=" + screen_Density);
            int img_margin = (int) ((screen_dip.getWidth() / 5 - 40) * screen_Density) / 2;
            int s_h = screen_dip.getHeight();
            int list_height = (int) (s_h - 70) / 3;
            int m_h = 19;
            if (screen_Density != 3) {
                m_h = (int) (19 + (3 / (3 - screen_Density)) * 2.5 + 1);
            }
            int vline_height = (int) ((list_height - 40 - 12 - m_h) * screen_Density - 3 * DisplayUtil.sp2px(14, DisplayUtil.getScreenScaledDensity()));  //40:图标  12 内边距 3行14sp的字

            SharedPreferences pDefault = this.getSharedPreferences(CommonUtility.SHARED_PREF_NAME, MODE_PRIVATE);
            String cityCode = pDefault.getString("current_code", "");

            SharedPreferences prefs = this.getSharedPreferences(cityCode, MODE_PRIVATE);
            if (prefs == null) {
                v.findViewById(R.id.weather_more_info_page).setVisibility(View.INVISIBLE);
                return;
            }

            LinearLayout list_layout = (LinearLayout)v.findViewById(R.id.weather_more_info_page);
            list_layout.removeAllViews();
            //LinearLayout zhishu_layout = (LinearLayout) v.findViewById(R.id.weather_more_info_zhishu);
            //zhishu_layout.removeAllViews();

            LayoutInflater inflater = LayoutInflater.from(this);
            for (int i =2; i <= 6; i++) {

                String[] tempArray = prefs.getString("temp_" + i, "").replace("℃", "").split("~");
                int temp1 = Integer.parseInt(tempArray[0]);
                int temp2 = Integer.parseInt(tempArray[1]);
                if (temp1 > temp2) {
                    int _temp = temp1;
                    temp1 = temp2;
                    temp2 = _temp;
                }

                String image_b = "d";
                String imageKey = "d00";
                if (new Date().getHours() > 18 || new Date().getHours() < 7) {
                    image_b = "n";
                }
                imageKey = "img_" + (i * 2 - 1);
                String img_num = prefs.getString(imageKey, "");
                if (img_num.length() == 1) {
                    imageKey = image_b + "0" + img_num;
                } else {
                    imageKey = image_b + img_num;
                }

                LinearLayout list_item = (LinearLayout) inflater.inflate(R.layout.day_weather, null);
                ImageView img = (ImageView) list_item.findViewById(R.id.weather_small_day_icon);
                img.setImageResource(Utility.getDrawableResourceId(imageKey));
                ((TextView) list_item.findViewById(R.id.weather_small_day_temp1)).setText(temp2 + "℃");
                ((TextView) list_item.findViewById(R.id.weather_small_day_temp2)).setText(temp1 + "℃");
                TextView days = (TextView) list_item.findViewById(R.id.weather_small_day_text);
                days.setText(Utility.formatDateForWeek(prefs.getString("date_y", ""), i - 1));
                if (screen_dip.getWidth() != 320) {
                    LinearLayout.LayoutParams pp = (LinearLayout.LayoutParams) img.getLayoutParams();
                    pp.setMargins(img_margin, 0, img_margin, 0);
                    img.setLayoutParams(pp);
                }
                //调整竖线的长度
                ImageView vline = (ImageView) list_item.findViewById(R.id.weather_small_day_vline);
                ViewGroup.LayoutParams lp = vline.getLayoutParams();
                lp.height = vline_height;
                vline.setLayoutParams(lp);

                list_layout.addView(list_item);

                if (i < 6) {
                    LinearLayout view = new LinearLayout(this);
                    RelativeLayout.LayoutParams para = new RelativeLayout.LayoutParams(1, ViewGroup.LayoutParams.MATCH_PARENT);
                    para.addRule(RelativeLayout.CENTER_HORIZONTAL);
                    view.setBackgroundColor(Color.argb(200, 255, 255, 255));
                    list_layout.addView(view, para);
                }
            }
            //添加指数
            ViewFlipper vf=(ViewFlipper)v.findViewById(R.id.viewFlipper);

            View indexLayout;
            if(vf.getChildCount()==1)
            {
                indexLayout= this.getLayoutInflater().inflate(R.layout.zhishu_layout,null);
                vf.addView(indexLayout);
            }

            indexLayout=vf.findViewById(R.id.weather_index_page);
            ((TextView)indexLayout.findViewById(R.id.index_cy)).setText(prefs.getString("index",""));
            ((TextView)indexLayout.findViewById(R.id.index_xc)).setText(prefs.getString("index_xc",""));
            ((TextView)indexLayout.findViewById(R.id.index_tr)).setText(prefs.getString("index_tr",""));
            ((TextView)indexLayout.findViewById(R.id.index_co)).setText(prefs.getString("index_co",""));
            ((TextView)indexLayout.findViewById(R.id.index_cl)).setText(prefs.getString("index_cl",""));
            ((TextView)indexLayout.findViewById(R.id.index_ls)).setText(prefs.getString("index_ls",""));
            ((TextView)indexLayout.findViewById(R.id.index_ag)).setText(prefs.getString("index_ag",""));
            ((TextView)indexLayout.findViewById(R.id.index_uv)).setText(prefs.getString("index_uv",""));

            //防止重叠
            if(vf.getCurrentView().getId()==R.id.weather_index_page)
            {
                vf.findViewById(R.id.weather_index_page).setVisibility(View.VISIBLE);
                vf.findViewById(R.id.weather_more_info_page).setVisibility(View.GONE);
            }
            else  if(vf.getCurrentView().getId()==R.id.weather_more_info_page)
            {
                vf.findViewById(R.id.weather_index_page).setVisibility(View.GONE);
                vf.findViewById(R.id.weather_more_info_page).setVisibility(View.VISIBLE);
            }

            //设置显示
            v.findViewById(R.id.weather_info_layout_page).setVisibility(View.VISIBLE);
            v.findViewById(R.id.city_name_page).setVisibility(View.VISIBLE);
            LogUtil.d("weather More", "add more layout over");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private void showWeather()
    {
        initView();
        SharedPreferences pDefault=this.getSharedPreferences(CommonUtility.SHARED_PREF_NAME,MODE_PRIVATE);
        String cityCode=pDefault.getString("current_code","");
        SharedPreferences prefs=this.getSharedPreferences(cityCode,MODE_PRIVATE);
        View view=viewList.get(currIndex);

         //设置背景
        String image_b = "d";
        String img_num ="|"+ prefs.getString("img1", "")+"|";
        if (new Date().getHours() > 18 || new Date().getHours() < 7) {
            image_b = "n";
            img_num ="|"+ prefs.getString("img2", "")+"|";
        }

        img_num=img_num.replace("n","").replace("d","").replace(".gif","");

        String num_1="|0|1|";
        String num_2="|2|3|";
        String num_3="|4|5|6|7|8|9|10|11|12|19|21|22|23|24|25|32|";
        String num_4="|13|14|15|16|17|26|27|28|33|";
        String num_5="|18|20|29|30|31|53|";
        String imgIndex="1";

        if(num_1.contains(img_num))
        {
            imgIndex="1";
        }
        else if(num_2.contains(img_num))
        {
            imgIndex="2";
        }
        else if(num_3.contains(img_num))
        {
            imgIndex="3";
        }
        else if(num_4.contains(img_num))
        {
            imgIndex="4";
        }
        else if(num_5.contains(img_num))
        {
            imgIndex="5";
        }
        String ImageKey="bg_"+imgIndex+"_"+image_b;
        LogUtil.d("WBG",ImageKey+","+img_num);
        view.setBackgroundResource(Utility.getDrawableResourceId(ImageKey));
        //---over=---

        int temp1=Integer.parseInt(prefs.getString("temp1","").replace("℃",""));
        int temp2=Integer.parseInt(prefs.getString("temp2", "").replace("℃", ""));
        if(temp1>temp2)
        {
            int _temp=temp1;
            temp1=temp2;
            temp2=_temp;
        }
        String [] date=prefs.getString("current_date", "").split("-");
        String [] time=prefs.getString("publish_time", "").split(":");
        ((TextView)view.findViewById(R.id.publish_text_page)).setText(date[1] + "月" + date[2] + "日 " + time[0] + ":" + time[1]);
        view.findViewById(R.id.weather_info_layout_page).setVisibility(View.VISIBLE);
        view.findViewById(R.id.city_name_page).setVisibility(View.VISIBLE);
        TextView cityName=(TextView) view.findViewById(R.id.city_name_page);
        cityName.setText(prefs.getString("city_name", ""));

        LogUtil.d("ShowWeather","code="+cityCode+",location="+pDefault.getString("location",""));

        if(Utility.IsCurrentLocation(cityCode))
        {
            LogUtil.d("ShowWeather","Is Location Page");
            view.findViewById(R.id.location_flag).setVisibility(View.VISIBLE);
        }
        else
        {
            LogUtil.d("ShowWeather","Is  Location Page");
            view.findViewById(R.id.location_flag).setVisibility(View.GONE);
        }
        ((TextView)view.findViewById(R.id.currtemp_page)).setText(prefs.getString("temp", ""));
        ((TextView)view.findViewById(R.id.weather_desp_page)).setText(prefs.getString("weather_desp", "") + " " + temp1 + "/" + temp2 + "℃");
        ((TextView)view.findViewById(R.id.wind_page)).setText(prefs.getString("wind", ""));
        ((TextView)view.findViewById(R.id.pm25_page)).setText(prefs.getString("pm25", ""));
        //更多信息

        boolean isQuery=isNeedQuery(cityCode);
        if(isQuery) {
            LogUtil.d("weather", "Query More city_code=" + cityCode);
            queryFromServer(CommonUtility.getWeatherUrl2(cityCode), "weatherMore");
        }
        else
        {
            showWeatherMoreDay();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
           case R.id.btnRefresh:
                ((TextView)viewList.get(currIndex).findViewById(R.id.publish_text_page)).setText("同步中...");
                SharedPreferences prefs= this.getSharedPreferences(CommonUtility.SHARED_PREF_NAME, MODE_PRIVATE);
                String weatherCode=prefs.getString("current_code","");
                if(!TextUtils.isEmpty(weatherCode))
                {
                    queryWeatherInfo(weatherCode);
                }
                break;
            case R.id.switch_city:
                if(PageCount<CommonUtility.MAX_CODE) {
                    Intent intent = new Intent(this, ChooseAreaActivity.class);
                    intent.putExtra("from_weather_activity", true);
                    startActivity(intent);
                    finish();
                }
                else
                {
                    Toast.makeText(this,"最多可以设置5个城市的天气预报，如需增加请选删除不需要的城市",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        super.dispatchTouchEvent(ev);
        onTouchEvent(ev);
        return true;
    }

    private float e1X,e1Y,e2X,e2Y;
    @Override
    public boolean onTouchEvent(MotionEvent ev)
    {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                e1X=ev.getX();
                e1Y=ev.getY();
                return true;
            case MotionEvent.ACTION_MOVE:
                //获取移动结束点的坐标
                break;
            case MotionEvent.ACTION_UP:
                float e2X = ev.getX();
                float e2Y = ev.getY();
                //差值
                float xDistance = Math.abs(e2X - e1X);
                float yDistance = Math.abs(e2Y - e1Y);
                if (xDistance <= yDistance && yDistance> SWIPE_MIN_DISTANCE) { // 往下传递
                    LogUtil.d("GD","WeatherActivity:onTouchEvent::ACTION_UP(xDistance:"+ xDistance +",yDistance:"+ yDistance +")");
                    translate(e1Y, e2Y);
                    return true;
                }
                else
                    return super.onTouchEvent(ev);

        }
        return super.onTouchEvent(ev);
    }

    private boolean inRect(int top ,int bootom,float pos)
    {
        return   top<= pos && bootom>=pos;
    }

    public void translate(float e1Y,float e2Y) {

        float y_v=Math.abs(e1Y-e2Y);

        int nTop= viewFlipper.getTop();
        int nBottom= viewFlipper.getBottom();

        if(inRect(nTop,nBottom,e1Y)) //&& Math.abs(velocityY)>SWIPE_THRESHOLD_VELOCITY
        {
            if(e1Y>e2Y)
            {
                LogUtil.d("GestureDetector", "向上滑动，Next show");
                viewFlipper.setInAnimation(slidBottomIn);
                viewFlipper.setOutAnimation(slidTopOut);
                viewFlipper.showNext();
            }
            else
            {
                LogUtil.d("GestureDetector","向下滑动,Prov show");
                viewFlipper.setInAnimation(slidTopIn);
                viewFlipper.setOutAnimation(slidBottomOut);
                viewFlipper.showPrevious();
            }
        }
    }

    public class MyPagerAdapter extends PagerAdapter {

        public List<View> mListView;

        public MyPagerAdapter(List<View> mListView) {
            this.mListView=mListView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ViewPager viewPager=(ViewPager)container;
            View view=(View)object;
            viewPager.removeView(view);
        }

        public void removeView(int position)
        {
            viewList.remove(position);
            pagerLayout.removeViewAt(position);
            PageCount=viewList.size();
            codeList.remove(position);
            pagerAdapter.notifyDataSetChanged();
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        @Override
        public int getCount() {
            return mListView.size();
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mListView.get(position));
            return viewList.get(position);
        }

        @Override
        public boolean isViewFromObject(View view, Object o) {
            return view==o;
        }
    }
}



